<!-- 任务委托变更流程 -->
<template>
  <view class="page">
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo">
          <u--input v-model="model.billNo" :disabled="checkDisabled('billNo')"></u--input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime">
          <u--input v-model="model.createTime" :disabled="checkDisabled('createTime')"></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="handlerId">
          <h-select-person-input
            style="width: 100%"
            :disabled="checkDisabled('handlerId')"
            v-model="model.handlerId"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.handlerId"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="handlerDeptId">
          <h-select-depart-input
            :disabled="checkDisabled('handlerDeptId')"
            v-model="model.handlerDeptId"
            :departName="model.hanlderDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.hanlderDeptText"
          ></h-select-depart-input>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">项目信息</view>
        <u-form-item label="项目名称" prop="projectId" required>
          <h-select-project-input-popup
            :disabled="checkDisabled('projectId')"
            :proDisabled="true"
            :projectStatus="'2'"
            ref="projectSelect"
            v-model="model.projectId"
            style="width: 100%"
            placeholder="请选择项目名称"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="onChangeProjectName"
          ></h-select-project-input-popup>
        </u-form-item>
        <u-form-item label="项目编号" prop="finalNo">
          <u--input :disabled="checkDisabled('finalNo')" placeholder="请输入项目编号" v-model="model.finalNo"></u--input>
        </u-form-item>
        <u-form-item label="经营团队" prop="teamName">
          <h-select-team-input
            :disabled="checkDisabled('teamName')"
            style="width: 100%"
            v-model="model.teamName"
            objectField="model.teamName"
            placeholder="请选择经营团队"
            border="surround"
            :tdlx="1"
          />
        </u-form-item>
        <u-form-item label="项目承接人" prop="undertaker">
          <h-select-person-input-popup
            :disabled="checkDisabled('undertaker')"
            v-model="model.undertaker"
            style="width: 100%"
            placeholder="请选择项目承接人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="立项日期" prop="projectEstablishDate">
          <h-time-select
            :disabled="checkDisabled('projectEstablishDate')"
            mode="datetime"
            v-model="model.projectEstablishDate"
            placeholder="请选择立项日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="签订单位" prop="signUnit">
          <h-select-company-input-popup
            :disabled="checkDisabled('signUnit')"
            style="width: 100%"
            v-model="model.signUnit"
            commercialType="1"
            placeholder="请选择公司"
            border="surround"
          ></h-select-company-input-popup>
        </u-form-item>
        <u-form-item label="业绩归属年度" prop="year">
          <h-select-input-tag
            :disabled="checkDisabled('year')"
            class="w-100"
            v-model="model.year"
            objectField="model.year"
            placeholder="请选择业绩归属年度"
            border="surround"
            dictName="yjgsnd"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="业主单位" prop="ownerUnit">
          <h-select-customer-input-popup
            :disabled="checkDisabled('ownerUnit')"
            style="width: 100%"
            v-model="model.ownerUnit"
            objectField="model.ownerUnit"
            commercialType="1"
            placeholder="请选择业主单位"
            border="surround"
          ></h-select-customer-input-popup>
        </u-form-item>
        <u-form-item label="联系人" prop="contacts">
          <h-select-input-tag
            :disabled="checkDisabled('contacts')"
            class="w-100"
            v-model="model.contacts"
            objectField="model.contacts"
            placeholder="请选择联系人"
            border="surround"
            :dictName="cust_lxr"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="联系方式" prop="contactTel">
          <u--input :disabled="checkDisabled('contactTel')" placeholder="请输入联系方式" v-model="model.contactTel"></u--input>
        </u-form-item>
        <u-form-item label="项目所在地址" prop="areaCode" :borderBottom="false">
          <h-select-address-input
            :disabled="checkDisabled('areaCode')"
            style="width: 100%"
            v-model="model.areaCode"
            placeholder="请选择项目地址"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-address-input>
        </u-form-item>
        <u-form-item label="项目详细地址" prop="projectAddress" :borderBottom="false">
          <u--input :disabled="checkDisabled('projectAddress')" placeholder="请输入项目详细地址" v-model="model.projectAddress"></u--input>
        </u-form-item>
        <u-form-item label="项目来源" prop="projectSource">
          <h-select-input-tag
            :disabled="checkDisabled('projectSource')"
            class="w-100"
            v-model="model.projectSource"
            objectField="model.projectSource"
            placeholder="请选择项目来源"
            border="surround"
            dictName="xmly_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="预计合同额(元)" prop="estimatedContractAmount">
          <u--input
            :disabled="checkDisabled('estimatedContractAmount')"
            type="number"
            v-number-normal
            placeholder="请输入预计合同额"
            v-model="model.estimatedContractAmount"
          ></u--input>
        </u-form-item>
        <u-form-item label="预计合同额大写" prop="estimatedContractcapitalChineseAmount">
          <u--input
            :disabled="checkDisabled('estimatedContractcapitalChineseAmount')"
            placeholder="请输入预计合同额大写"
            v-model="model.estimatedContractcapitalChineseAmount"
          ></u--input>
        </u-form-item>
        <u-form-item label="立项事由及说明" prop="establishReason">
          <u--textarea
            :disabled="checkDisabled('establishReason')"
            maxlength="500"
            confirm-type="send"
            v-model="model.establishReason"
            placeholder="请输入立项事由及说明"
          ></u--textarea>
        </u-form-item>
        <view class="basic-title basic-border">项目附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file :disabled="checkDisabled('attachment')" v-model="model.attachment" :isIcon="false"></h-upload-file>
          <file-list v-if="model.attachment" v-model="model.attachment"></file-list>
        </view>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">任务信息</view>
        <u-form-item label="任务编号" prop="taskId" required>
          <h-select-task-input-popup
            :projectId="model.projectId"
            v-model="model.taskId"
            class="w-100"
            :disabled="!model.projectId || checkDisabled('taskId')"
            :placeholder="model.projectId ? '请选择任务编号' : '请先选择项目'"
            searchPlaceholder="请输入任务编号"
            label="billNo"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :customParams="{
              changeStatus: '!changing',
              distributionType: 'producting',
            }"
            @select="onTaskIdInput"
          ></h-select-task-input-popup>
        </u-form-item>
        <u-form-item label="业务分类" prop="categoryName">
          <u--input :disabled="checkDisabled('categoryName')" placeholder="请输入业务分类" v-model="model.categoryName"></u--input>
        </u-form-item>
        <u-form-item label="合同占比(%)" prop="contractRate">
          <u--input
            :disabled="checkDisabled('contractRate')"
            type="number"
            v-number-normal
            placeholder="请输入合同占比"
            v-model="model.contractRate"
          ></u--input>
        </u-form-item>
        <u-form-item label="合同分配额(元)" prop="contractAmount">
          <u--input
            :disabled="checkDisabled('contractAmount')"
            type="number"
            v-number-normal
            placeholder="请输入合同分配额"
            v-model="model.contractAmount"
          ></u--input>
        </u-form-item>
        <u-form-item label="切割合同额(元)" prop="cutContractAmount">
          <u--input
            :disabled="checkDisabled('cutContractAmount')"
            type="number"
            v-number-normal
            placeholder="请输入切割额"
            v-model="model.cutContractAmount"
          ></u--input>
        </u-form-item>
        <u-form-item label="生产团队" prop="productTeam">
          <h-select-team-input
            :disabled="checkDisabled('productTeam')"
            style="width: 100%"
            v-model="model.productTeam"
            objectField="model.productTeam"
            placeholder="请选择生产团队"
            border="surround"
            :tdlx="2"
          />
        </u-form-item>
        <!-- <u-form-item
          label="生产公司"
          prop="productCompanyId"
          :borderBottom="false"
        >
          <h-select-company-input
            disabled
            style="width: 100%"
            v-model="model.productCompanyId"
            border="surround"
            placeholder="请选择生产公司"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{color: '#B2B2B2'}"
          ></h-select-company-input>
          </u-form-item> -->
        <u-form-item label="任务类型" prop="taskType" required>
          <h-select-input-tag
            :disabled="checkDisabled('taskType')"
            class="w-100"
            v-model="model.taskType"
            objectField="model.taskType"
            placeholder="请选择任务类型"
            border="surround"
            dictName="task_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="实施部门" prop="executeDepart" :required="checkRequired('executeDepart')">
          <h-select-depart-input
            :disabled="checkDisabled('executeDepart')"
            v-model="model.executeDepart"
            :departName="model.executeDepartText"
            placeholder="请选择实施部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.executeDepartText"
            @detail="onExecuteDepartInput"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="部门负责人" prop="minister" :required="checkRequired('minister')">
          <h-select-person-input-popup
            :disabled="checkDisabled('minister')"
            muitFlag
            v-model="model.minister"
            style="width: 100%"
            placeholder="请选择部门负责人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="项目负责人" prop="projectLeading" :required="checkRequired('projectLeading')">
          <h-select-person-input-popup
            :disabled="checkDisabled('projectLeading')"
            v-model="model.projectLeading"
            style="width: 100%"
            placeholder="请选择项目负责人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
						@back="handleProjectLeadingBack"
          ></h-select-person-input-popup>
        </u-form-item>

        <!-- 当任务类型为环评咨询，水保咨询时，展示本项 -->
        <template v-if="model.taskType == 1 || model.taskType == 4">
          <u-form-item label="审核工程师" prop="approvalEngineer" v-if="model.taskType == 1" :required="checkRequired('approvalEngineer')">
            <h-select-person-input-popup
              :disabled="checkDisabled('approvalEngineer')"
              v-model="model.approvalEngineer"
              style="width: 100%"
              placeholder="请选择审核工程师"
              searchPlaceholder="请输入"
              border="surround"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
            ></h-select-person-input-popup>
          </u-form-item>
          <u-form-item label="审批级别" prop="approvalLevel">
            <h-select-input-tag
              :disabled="checkDisabled('approvalLevel')"
              class="w-100"
              v-model="model.approvalLevel"
              objectField="model.approvalLevel"
              placeholder="请选择审批级别"
              border="surround"
              dictName="approval_level"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="审批系数" prop="approvalCoefficient">
            <u--input
              :disabled="checkDisabled('approvalCoefficient')"
              type="number"
              v-number-normal
              placeholder="请输入审批系数"
              v-model="model.approvalCoefficient"
            ></u--input>
          </u-form-item>
          <u-form-item label="行业类别" prop="industryCategory">
            <h-select-input-tag
              :disabled="checkDisabled('industryCategory')"
              class="w-100"
              v-model="model.industryCategory"
              objectField="model.industryCategory"
              placeholder="请选择行业类别"
              border="surround"
              dictName="industry_category"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="行业系数" prop="industryCoefficient">
            <u--input
              :disabled="checkDisabled('industryCoefficient')"
              type="number"
              v-number-normal
              placeholder="请输入行业系数"
              v-model="model.industryCoefficient"
            ></u--input>
          </u-form-item>
          <u-form-item label="复杂程度" prop="complexity">
            <h-select-input-tag
              :disabled="checkDisabled('complexity')"
              class="w-100"
              v-model="model.complexity"
              objectField="model.complexity"
              placeholder="请选择复杂程度"
              border="surround"
              dictName="industry_coefficient"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="复杂系数" prop="complexCoefficient">
            <u--input
              :disabled="checkDisabled('complexCoefficient')"
              type="number"
              v-number-normal
              placeholder="请输入复杂系数"
              v-model="model.complexCoefficient"
            ></u--input>
          </u-form-item>
        </template>

        <!-- 当任务类型为检验检测时，展示本项 -->
        <template v-if="model.taskType == 2">
          <u-form-item label="是否出具报告" prop="isOutReport">
            <h-select-input-tag
              :disabled="checkDisabled('isOutReport')"
              class="w-100"
              v-model="model.isOutReport"
              objectField="model.isOutReport"
              placeholder="请选择是否出具报告"
              border="surround"
              dictName="YES_OR_NO"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="费用核算方式" prop="expenseAccountingMethod">
            <h-select-input-tag
              :disabled="checkDisabled('expenseAccountingMethod')"
              class="w-100"
              v-model="model.expenseAccountingMethod"
              objectField="model.expenseAccountingMethod"
              placeholder="请选择费用核算方式"
              border="surround"
              dictName="expense_accounting_method"
            ></h-select-input-tag>
          </u-form-item>
        </template>
        <u-form-item label="说明" prop="instruction">
          <u--textarea
            :disabled="checkDisabled('instruction')"
            maxlength="500"
            confirm-type="send"
            v-model="model.instruction"
            placeholder="请输入说明"
          ></u--textarea>
        </u-form-item>
        <view class="basic-title basic-border">任务附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file :disabled="checkDisabled('taskFile')" v-model="model.taskFile" :isIcon="false"></h-upload-file>
          <file-list v-if="model.taskFile" v-model="model.taskFile" :isDelete="true"></file-list>
        </view>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">项目成员</view>
        <view class="space-y-1 py-1">
          <u-button size="small" v-if="!checkDisabled('distributionDtList')" type="primary" @click="handleAddMember">新增</u-button>
        </view>

        <u-collapse>
          <u-collapse-item :title="`项目成员-${item.projectMember_dictText}`" v-for="(item, index) in formData" :key="index">
            <FormInfo
              :disabled="checkDisabled('distributionDtList')"
              :item="item"
              :index="index"
              @edit="handleEditForm"
              @remove="handleRemoveForm"
              @copy="handleCopyForm"
            />
          </u-collapse-item>
        </u-collapse>
        <u-popup class="form-popup" mode="right" :show="showFormModal" @close="closeFormModal" @open="openFormModal">
          <MemberForm ref="dataForm" :index="index" @submit="handleFormSubmit" @close="showFormModal = false" :model="model" />
        </u-popup>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">项目预算</view>
        <u-form-item label="预算总工时(人小时)" prop="expectWorkTime">
          <u--input
            type="number"
            disabled
            v-number-normal
            placeholder="请输入预算总工时(人小时)"
            v-model="model.expectWorkTime"
          ></u--input>
        </u-form-item>
				<u-form-item label="生产总绩效(元)" prop="totalProductPerformance">
				  <u--input type="number" disabled placeholder="请输入生产总绩效" v-model="model.totalProductPerformance"></u--input>
				</u-form-item>
        <u-form-item label="人工成本(元)" prop="workCost">
          <u--input
            type="number"
            disabled
            v-number-normal
            placeholder="请输入人工成本"
            v-model="model.workCost"
          ></u--input>
        </u-form-item>
        <!-- <u-form-item label="委外费(元)" prop="outsourcingFee" :required="checkRequired('outsourcingFee')">
          <u--input
            :disabled="checkDisabled('outsourcingFee')"
            type="number"
            v-number-normal
            placeholder="请输入委外费"
            v-model="model.outsourcingFee"
          ></u--input>
        </u-form-item> -->
        <u-form-item label="委外费(元)" prop="outsourcingFee" :required="checkRequired('outsourcingFee')">
          <h-number-input
            :disabled="checkDisabled('outsourcingFee')"
            placeholder="请输入委外费"
            v-model="model.outsourcingFee"
            :digit="2"
            :max="99999999"
            :min="1"
            suffixIcon="edit-pen-fill"
          ></h-number-input>
        </u-form-item>
        <!-- <u-form-item label="差旅费(元)" prop="travelFee" :required="checkRequired('travelFee')">
          <u--input
            :disabled="checkDisabled('travelFee')"
            type="number"
            v-number-normal
            placeholder="请输入差旅费"
            v-model="model.travelFee"
          ></u--input>
        </u-form-item> -->
        <u-form-item label="差旅费(元)" prop="travelFee" :required="checkRequired('travelFee')">
          <h-number-input
            :disabled="checkDisabled('travelFee')"
            placeholder="请输入差旅费"
            v-model="model.travelFee"
            :digit="2"
            :max="99999999"
            :min="1"
            suffixIcon="edit-pen-fill"
          ></h-number-input>
        </u-form-item>
        <!-- <u-form-item label="专家评审费(元)" prop="professionReviewFee" :required="checkRequired('professionReviewFee')">
          <u--input
            :disabled="checkDisabled('professionReviewFee')"
            type="number"
            v-number-normal
            placeholder="请输入专家评审费"
            v-model="model.professionReviewFee"
          ></u--input>
        </u-form-item> -->
        <u-form-item label="专家评审费(元)" prop="professionReviewFee" :required="checkRequired('professionReviewFee')">
          <h-number-input
            :disabled="checkDisabled('professionReviewFee')"
            placeholder="请输入专家评审费"
            v-model="model.professionReviewFee"
            :digit="2"
            :max="99999999"
            :min="1"
            suffixIcon="edit-pen-fill"
          ></h-number-input>
        </u-form-item>
        <!-- <u-form-item label="其他成本(元)" prop="otherCost" :required="checkRequired('otherCost')">
          <u--input
            :disabled="checkDisabled('otherCost')"
            type="number"
            v-number-normal
            placeholder="请输入其他成本"
            v-model="model.otherCost"
          ></u--input>
        </u-form-item> -->
        <u-form-item label="其他成本(元)" prop="otherCost" :required="checkRequired('otherCost')">
          <h-number-input
            :disabled="checkDisabled('otherCost')"
            placeholder="请输入其他成本"
            v-model="model.otherCost"
            :digit="2"
            :max="99999999"
            :min="1"
            suffixIcon="edit-pen-fill"
          ></h-number-input>
        </u-form-item>
        <!-- <u-form-item label="项目预算合计(元)" prop="totalProjectBudget" required>
          <u--input
            :disabled="checkDisabled('outsourcingFee')"
            disabled
            type="number"
            v-number-normal
            placeholder="人工总成本+委外费+差旅费+专家评审费+其他成本"
            v-model="model.totalProjectBudget"
          ></u--input>
        </u-form-item> -->
        <u-form-item label="项目预算合计(元)" prop="totalProjectBudget" required>
          <h-number-input
            disabled
            placeholder="人工总成本+委外费+差旅费+专家评审费+其他成本"
            v-model="model.totalProjectBudget"
            :digit="2"
            :max="99999999"
            :min="1"
          ></h-number-input>
        </u-form-item>
				<template v-if="model.categoryName">
					<u-form-item label="项目预算表" v-if="isProjectInformation" prop="projectBudgetFile" :required="checkRequired('projectBudgetFile')">
						<view class="py-1 space-y-1" style="width: 100%">
							<h-upload-file v-model="model.projectBudgetFile" v-if="!checkDisabled('projectBudgetFile')" :isIcon="false"></h-upload-file>
							<file-list v-model="model.projectBudgetFile" :isDelete="!checkDisabled('projectBudgetFile')"></file-list>
						</view>
					</u-form-item>
					<u-form-item label="生产绩效表" v-else prop="productBudgetFile" :required="checkRequired('productBudgetFile')">
					  <view class="py-1 space-y-1" style="width: 100%">
					  	<h-upload-file v-if="!checkDisabled('productBudgetFile')" v-model="model.productBudgetFile" :isIcon="false"></h-upload-file>
					    <file-list v-model="model.productBudgetFile" :isDelete="!checkDisabled('productBudgetFile')"></file-list>
					  </view>
					</u-form-item>
				</template>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">任务进度</view>
        <u-form-item label="进度模板" prop="templateId" :borderBottom="false" :required="checkRequired('templateId')">
          <!-- disabled -->
          <h-select-process-template-input
            :disabled="checkDisabled('templateId') || paymentDisabled"
            style="width: 100%"
            v-model="model.templateId"
            objectField="model.templateId"
            placeholder="请选择进度模板"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @input="getTemplateList"
          ></h-select-process-template-input>
        </u-form-item>
				<u-form-item label="允许添加子节点" prop="isAddChildNode">
				  <h-select-input-tag
						disabled
				    class="w-100"
				    v-model="model.isAddChildNode"
				    objectField="model.isAddChildNode"
				    placeholder="请选择允许添加子节点"
				    border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				    dictName="yes_no"
				  ></h-select-input-tag>
				</u-form-item>
				<u-form-item label="收入确认方式" prop="confirmIncomeMethod">
				  <h-select-input-tag
				    class="w-100"
						disabled
				    v-model="model.confirmIncomeMethod"
				    objectField="model.confirmIncomeMethod"
				    placeholder="请选择收入确认方式"
				    border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				    dictName="confirm_income_method"
				  ></h-select-input-tag>
				</u-form-item>
        <u-collapse>
          <u-collapse-item :title="`${item.nodeName}`" v-for="(item, index) in templateDataList" :key="index">
            <u-form labelWidth="auto" disabled>
              <u-form-item :label="key" v-for="(child, key) in taskProgressFields" :key="key">
                {{ item[child] }}
              </u-form-item>
            </u-form>
          </u-collapse-item>
        </u-collapse>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">款项进度</view>
        <u-collapse ref="collapse" v-if="priceFormData && priceFormData.length">
          <u-collapse-item :title="`${item.nodeName}`" v-for="(item, index) in priceFormData" :key="index">
            <PriceFormInfo
              :item="item"
              :index="index"
              :progressVoList="templateDataList"
              :disabled="checkDisabled('progressNodeVoList')"
              @edit="handleEditPriceForm"
              @remove="handleRemovePriceForm"
              @copy="handleCopyPriceForm"
            />
          </u-collapse-item>
        </u-collapse>
        <u-empty v-else mode="data" icon="/static/empty/data.png"></u-empty>
        <u-popup mode="bottom" :show="showPriceFormModal" @close="closePriceFormModal" @open="openPriceFormModal">
          <PriceForm
            :progressVoList="templateDataList"
            ref="priceForm"
            :index="index"
            @submit="handlePriceFormSubmit"
            @close="showPriceFormModal = false"
          />
        </u-popup>
        <u-form-item label="履约保证金(元)" prop="bail">
          <u--input
            type="number"
            :disabled="checkDisabled('bail')"
            v-number-normal
            placeholder="请输入履约保证金"
            v-model="model.bail"
          ></u--input>
        </u-form-item>
        <u-form-item label="款项节点说明" prop="paymentDesc" v-if="Number(model.bail)">
          <u--textarea
            :disabled="checkDisabled('paymentDesc')"
            maxlength="500"
            :confirm-type="null" count
            v-model="model.paymentDesc"
            placeholder="请输入款项节点说明"
          ></u--textarea>
        </u-form-item>
        <template v-if="Number(model.bail)">
          <u-form-item label="是否应收" prop="isCollectionPayment" :required="checkRequired('isCollectionPayment')">
            <h-dict-radio
              v-model="model.isCollectionPayment"
              :disabled="checkDisabled('isCollectionPayment')"
              dictName="YES_OR_NO"
              @input="(val) => val == 0 && (model.collectionDate = null)"
            ></h-dict-radio>
          </u-form-item>
        </template>
        <template v-if="model.isCollectionPayment == 1">
          <u-form-item label="预计应收日期" prop="collectionDate" :required="checkRequired('collectionDate')">
            <h-time-select
              :disabled="checkDisabled('collectionDate')"
              mode="date"
              v-model="model.collectionDate"
              placeholder="请选择应收日期"
              border="surround"
              suffixIcon="calendar-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
            ></h-time-select>
          </u-form-item>
        </template>
      </view>
    </u-form>

    <view class="space-x-1 px-1 btn_position">
    	<backButton  @onSubmit="onSubmit" :nodeObj="nodeObj" :model="processModel" :resultObj="resultObj"></backButton>
    </view>
    <view style="height: 100rpx;"></view>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { erpProgressTemplateDtList, getProcessTaskTransInfo } from '@/api/index'
import { gainBillNo, add, edit, info, queryPageList } from '@/api/project/ErpProgressTaskChangeListForm'
import http from '@/utils/request/index'
import fileList from '@/pages/synergy/components/fileList.vue'
import backButton from '@/components/backButton.vue'
import MemberForm from '@/pages/project/components/MemberForm.vue'
import FormInfo from '@/pages/project/components/MemberFormInfo.vue'
import PriceForm from '@/pages/project/components/PriceForm.vue'
import PriceFormInfo from '@/pages/project/components/PriceFormInfo.vue'
import Decimal from 'decimal.js'
import {
  queryUsersByUsernames, // 部门负责人带入
} from '@/api/index.js'
export default {
  name: 'ErpProgressTaskChangeListForm',
  components: {
    fileList,
    MemberForm,
    FormInfo,
    PriceForm,
    PriceFormInfo,
		backButton
  },
  data() {
    return {
			resultObj: {}, // 流程图流转信息
      processModel: {},
      isSubmit: false,
      extendUrlParams: {},
      taskProgressFields: {
        节点名称: 'nodeName',
        节点进度: 'nodeProgress',
        完成状态: 'taskCompleteStatus_dictText',
        完成时间: 'completeTime',
				收入确认节点: 'isConfirmIncomeNode_dictText'
      },
      templateDataList: [],
      cust_lxr: 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=0',
      backUpProvisionBroad: '',
      showBusinessSegment: false,
      exportTeamId: '',
      flag: false,
      index: null,
      showFormModal: false,
      showPriceFormModal: false,
      confirmModal: false,
      loading: false,
      id: '',
      exportWarehouseList: [],
      foldWarehouseList: [],
      dataSource2: [],
      basicForm: {},
      // formData: [
      //   {
      //     id: 411283512599,
      //     materialBillId: 'WL01343',
      //     brand: '农夫山泉',
      //     specification: '6L',
      //     amount: '6',
      //     provisionSmall: '1535177002383859714',
      //     materialName: '1627503793494896641',
      //     referencePrice: null,
      //     unit: '4',
      //     budgetAmount: '12',
      //   },
      // ],
      formData: [],
      // formData: [
      //   {
      //     expectWorkTime: 1.5,
      //     projectMember_dictText: '张鹏',
      //     dayCost: 137.01,
      //     contractAmount: 2000,
      //     laborCost: 806.17,
      //     contractRate: 8.89,
      //     id: '1658066715907563521',
      //     projectMember: '1632987084150865922',
      //     projectPerformance: 600.66,
      //   },
      //   {
      //     expectWorkTime: 6.6,
      //     projectMember_dictText: '齐乃彬',
      //     dayCost: 238.16,
      //     contractAmount: 2000,
      //     laborCost: 2272.52,
      //     contractRate: 8.89,
      //     id: '1658066715936923649',
      //     projectMember: '1633259245298053122',
      //     projectPerformance: 700.66,
      //   },
      //   {
      //     expectWorkTime: 2.4,
      //     projectMember_dictText: '杨璐璐',
      //     dayCost: 152.18,
      //     contractAmount: 500,
      //     laborCost: 665.23,
      //     contractRate: 2.22,
      //     id: '1658066715962089474',
      //     projectMember: '1633674894671409153',
      //     projectPerformance: 300,
      //   },
      //   {
      //     expectWorkTime: 9,
      //     projectMember_dictText: '张冰倩',
      //     dayCost: 142.07,
      //     contractAmount: 18000,
      //     laborCost: 1286.63,
      //     contractRate: 80,
      //     id: '1658066715987255297',
      //     projectMember: '1631576319711838209',
      //     projectPerformance: 8,
      //   },
      // ],
      priceFormData: [],
      // priceFormData: [
      //   {
      //     nodeName: '款项一',
      //     isRelatedTaskNode_dictText: '是',
      //     isRelatedTaskNode: '1',
      //     delFlag: null,
      //     isCollectionPayment_dictText: '否',
      //     collectionDate: null,
      //     isRelatedTask: '1',
      //     isRelatedTask_dictText: '是',
      //     finalId: '1658066716658343937',
      //     taskNodeId_dictText: '节点2',
      //     sortOrder: 1,
      //     isCollectionPayment: '0',
      //     nodeDesc: '这是款项一的节点说明。',
      //     id: '1657935704381038593',
      //     paymentMoney: 20000,
      //     projectId: null,
      //     taskNodeId: '16841483915486246409947902610665',
      //     paymentDesc: null,
      //   },
      //   {
      //     nodeName: '款项二',
      //     isRelatedTaskNode_dictText: '否',
      //     isRelatedTaskNode: '0',
      //     delFlag: null,
      //     isCollectionPayment_dictText: '否',
      //     collectionDate: null,
      //     isRelatedTask: '1',
      //     isRelatedTask_dictText: '是',
      //     finalId: '1658066716691898370',
      //     taskNodeId_dictText: null,
      //     sortOrder: 2,
      //     isCollectionPayment: '0',
      //     nodeDesc: '13899 【项目管理-任务管理-任务委托-三期】新增页面，项目成员、项目预算模块新增字段，置灰不可编辑',
      //     id: '1657935704418787329',
      //     paymentMoney: 30000,
      //     projectId: null,
      //     taskNodeId: null,
      //     paymentDesc: null,
      //   },
      //   {
      //     nodeName: '款项三',
      //     isRelatedTaskNode_dictText: '是',
      //     isRelatedTaskNode: '1',
      //     delFlag: null,
      //     isCollectionPayment_dictText: '否',
      //     collectionDate: null,
      //     isRelatedTask: '1',
      //     isRelatedTask_dictText: '是',
      //     finalId: '1658066716721258498',
      //     taskNodeId_dictText: '节点三',
      //     sortOrder: 3,
      //     isCollectionPayment: '0',
      //     nodeDesc: '这是款项手机',
      //     id: '1657935704452341761',
      //     paymentMoney: 40000,
      //     projectId: null,
      //     taskNodeId: '16841483915489671058063991079684',
      //     paymentDesc: null,
      //   },
      // ],
      model: {
        applyType: 2,
        billNo: '',
        createTime: '',
        handlerId: '',
        handlerDeptId: '',
        projectId: '',
        finalNo: '',
        teamName: '',
        undertaker: '',
        projectEstablishDate: '',
        signUnit: '',
        year: '',
        ownerUnit: '',
        contacts: '',
        contactTel: '',
        areaCode: '',
        projectAddress: '',
        projectSource: '',
        estimatedContractAmount: '',
        estimatedContractcapitalChineseAmount: '',
        establishReason: '',
        taskId: '',
        categoryName: '',
        contractRate: '',
        contractAmount: '',
        cutContractAmount:'',
        productTeam: '',
        productCompanyId:'',
        taskType: '',
        executeDepart: '',
        minister: '',
        projectLeading: '',
        taskFile: null,
				projectBudgetFile: null,
				productBudgetFile: null,
        templateId: '',
        purchaseFile: null,
        isCollectionPayment: '',
				collectionDate: '',

        expectWorkTime: '',
        workCost: '',
        outsourcingFee: '',
        travelFee: '',
        professionReviewFee: '',
        otherCost: '',
        totalProjectBudget: '',
      },
      rules: {
        projectId: [{ required: true, message: '请选择项目名称!', pattern: '[^ \x22]+' }],
        taskType: [{ required: true, message: '请选择任务类型!' }],
        taskId: [{ required: true, message: '请选择任务编号!' }],
        outsourcingFee: [{ required: true, message: '请输入委外费!' }],
        travelFee: [{ required: true, message: '请输入差旅费!' }],
        professionReviewFee: [{ required: true, message: '请输入专家评审费!' }],
        otherCost: [{ required: true, message: '请输入其他成本!' }],
        collectionDate: [{ required: true, message: '请选择应收日期!' }],
				projectBudgetFile: [{ required: true, message: '请选择项目预算表!'}],
				productBudgetFile: [{ required: true, message: '请选择生产绩效表!'}],
      },

      nodeObj: {},
      dataNodeObj: '',
    }
  },
  async onLoad(options) {
    this.processModel = JSON.parse(decodeURIComponent(options.item))
    this.extendUrlParams = JSON.parse(decodeURIComponent(options.params))
    var that = this
    // #ifdef APP-NVUE
    var eventChannel = this.$scope.eventChannel // 兼容APP-NVUE
    // #endif
    // #ifndef APP-NVUE
    var eventChannel = this.getOpenerEventChannel()
    // #endif
    // 监听sendMessage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('sendMessage', function (data) {
      that.tabvalue = data.tabvalue
      that.nodeObj = JSON.parse(decodeURIComponent(data.nodeObj))
      that.dataNodeObj = data.nodeObj
      that.id = that.nodeObj.dataId
      that.loadData(that.nodeObj.dataId)
			that.getProcessTaskTrans(that.processModel.id)
    })
    this.initRules()
  },
  created() {
    if (this.id) {
      this.initInfo()
    } else {
      this.initForm()
      this.initBillNo()
    }
    // this.initBuyerInfo()
  },
  computed: {
    paymentDisabled() {
			if (this.templateDataList && this.templateDataList.length) {
				return this.templateDataList.some((i) => i.taskCompleteStatus == 2)
			} else {
				return false
			}
      
    },
    ...mapState(['userInfo']),
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
    // 总工时
    expectWorkTime() {
      if (!this.formData || !this.formData.length) {
        return 0
      }

      return this.formData.reduce((total, cur) => {
        // return total + (Number(cur.expectWorkTime) || 0)
        return new Decimal(total).plus(Number(cur.expectWorkTime) || 0).toNumber()
      }, 0)
    },
    // 总人工成本
    workCost() {
      if (!this.formData || !this.formData.length) {
        return 0
      }
      return this.formData.reduce((total, cur) => {
        // return total + (Number(cur.laborCost) || 0)
        return new Decimal(total).plus(Number(cur.laborCost) || 0).toNumber()
      }, 0)
    },
		totalProductPerformance() {
		  if (!this.formData || !this.formData.length) {
		    return 0
		  }
		  return this.formData.reduce((total, cur) => {
		    return new Decimal(total).plus(Number(cur.projectPerformance) || 0).toNumber()
		  }, 0)
		},
    // 总花费
    totalProjectBudget() {
      const { outsourcingFee, travelFee, professionReviewFee, otherCost } = this.model
      // return this.expectWorkTime + this.workCost + (outsourcingFee || 0) + (travelFee || 0) + (professionReviewFee || 0) + (otherCost || 0)

      function parse(num) {
        return Number(num) || 0
      }
      return Decimal(this.workCost)
        .plus(parse(outsourcingFee))
        .plus(parse(travelFee))
        .plus(parse(professionReviewFee))
        .plus(parse(otherCost))
        .toNumber()
    },
		// 判断是否为工程运维或者数字信息的业务分类
		isProjectInformation() {
			// 判断categoryName是否含有工程运维或者数字信息
			if (this.model.categoryName && (this.model.categoryName.indexOf('工程运维') !== -1 || this.model.categoryName.indexOf('数字信息') !== -1)) {
				return true
			} else {
				return false
			}
		}
  },
  methods: {
    checkDisabled(key) {
      const keyStrategy = {
        ybmfzr: ['executeDepart', 'minister', 'projectLeading', 'instruction', 'taskFile'],
        xbmfzr: ['projectLeading', 'instruction', 'taskFile'],
        xxmfzr: [
          // 必填
          'distributionDtList',
          'outsourcingFee',
          'travelFee',
          'professionReviewFee',
          'otherCost',
          'templateId',
          'isOutReport',
					'projectBudgetFile',
					'productBudgetFile',
          // 非必填
          'progressNodeVoList',
          'instruction',
          'taskFile',
          'paymentDesc',
          'isCollectionPayment',
          'collectionDate',
        ],
        xmzy: ['instruction', 'taskFile', 'approvalEngineer'],
      }
      const ignoreKeys = keyStrategy[this.extendUrlParams.node] || []
      if (ignoreKeys.includes(key)) {
        return false
      }
      return true
    },
    initRules() {
      const ruleStrategy = {
        ybmfzr: {
          executeDepart: [{ required: true, message: '请选择实施部门!' }],
          minister: [{ required: true, message: '请选择部门负责人!' }],
          projectLeading: [{ required: true, message: '请选择项目负责人!' }],
        },
        xbmfzr: {
          projectLeading: [{ required: true, message: '请选择项目负责人!' }],
        },
        xxmfzr: {
          outsourcingFee: [{ required: true, message: '请填写委外费' }],
          travelFee: [{ required: true, message: '请填写差旅费' }],
          professionReviewFee: [{ required: true, message: '请填写专家评审费' }],
          otherCost: [{ required: true, message: '请填写其他成本' }],
          templateId: [{ required: true, message: '请选择任务进度' }],
          isCollectionPayment: [{ required: true, message: '请填写是否应收!' }],
          collectionDate: [{ required: true, message: '请填写应收日期!' }],
					projectBudgetFile: [{ required: true, message: '请选择项目预算表!'}],
					productBudgetFile: [{ required: true, message: '请选择生产绩效表!'}],
        },
        xmzy: {
          approvalEngineer: [{ required: true, message: '请选择审核工程师!' }],
        },
      }
			console.log(this.extendUrlParams.node);
      const rules = ruleStrategy[this.extendUrlParams.node] || {}
			console.log(rules);
      this.$set(this, 'rules', rules)
    },
    checkRequired(key) {
      return Object.keys(this.rules).includes(key) || false
    },
    async loadData(id) {
      info({ id }).then(async (res) => {
        if (res.success) {
          await Object.assign(this.model, res.result)
          // 获取项目编号
          this.cust_lxr = await `erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=${res.result.ownerUnit}`
          // this.queryPaymentNodeListByMainId(res.result.id) // 获取款项进度列表
          this.getPaymentList(2, id, res.result.projectId, res.result.taskId) // 获取款项进度列表
          // this.queryTaskNodeListByMainId(res.result.id) // 获取任务进度列表
          this.getTaskNodeList(2, id, res.result.projectId, res.result.taskId) // 获取任务进度
          if (res.result.id) { // 获取项目成员
            http.get('/api/erp/omc/task/erpOmcTaskDistributionDt/list', { mainId: res.result.id }).then(async (response) => {
              this.formData = response.result || []
							if (this.extendUrlParams.node === 'xxmfzr') {
								if (this.model.projectLeading) {
									this.formData = this.addProjectLeading(this.formData, this.model.projectLeading_dictText)
								} else {
									if (this.formData && this.formData.length) {
										// 全部置为false
										this.formData.forEach((item) => {
											item.isProjectLeading = false
										})
									}
								}
							}
            })
          }
          this.model.projectId &&
            http.get('/api/erp/omc/project/erpOmcProject/queryById', { id: this.model.projectId }).then(async (res) => {
              if (res.success) {
                var event = res.result
                this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
              }
            })
        } else {
          this.$u.toast(res.message)
        }
      })
    },
		// 项目成员判断是否添加项目负责人，如果已添加则不添加
		addProjectLeading(distributionDtList = [], name) {
			// 查询项目成员列表中是否包含项目负责人，如果不包含就需要添加项目负责人
			if (distributionDtList.length > 0) {
				// 先全部置为false，再判断是否包含model.projectLeading，如果不包含就添加项目负责人
				distributionDtList.forEach((item) => {
					item.isProjectLeading = false
				})
				// 循环遍历distributionDtList，判断是否包含model.projectLeading，如果不包含就添加项目负责人
				let listIndex = distributionDtList.findIndex(item => item.projectMember == this.model.projectLeading)
				if (listIndex === -1) {
					distributionDtList.unshift({
						projectMember: this.model.projectLeading, // 添加项目负责人
						projectMember_dictText: name, // 添加项目负责人
						id: parseInt(Math.random() * 1000000000000),
						mainId: this.mainId,
						contractAmount: null,
						cutContractAmount: null,
						contractRate: null,
						dayCost: null,
						expectWorkTime: null,
						laborCost: null,
						projectPerformance: null,
						isProjectLeading: true // 用于判断该条数据是否为项目负责人
					})
					http.get('/api/erp/files/employee/erpEmployeeFile/queryPayGradeByEmpId', { empId: this.model.projectLeading }).then(response => {
						distributionDtList[0].dayCost = response.result
					})
				} else {
					distributionDtList.splice(listIndex, 1, {...distributionDtList[listIndex],isProjectLeading: true }) // 用于判断该条数据是否为项目负责人
				}
			} else {
				distributionDtList.unshift({
					projectMember: this.model.projectLeading, // 添加项目负责人
					projectMember_dictText: name, // 添加项目负责人
					id: parseInt(Math.random() * 1000000000000),
					mainId: this.mainId,
					contractAmount: null,
					cutContractAmount: null,
					contractRate: null,
					dayCost: null,
					expectWorkTime: null,
					laborCost: null,
					projectPerformance: null,
					isProjectLeading: true // 用于判断该条数据是否为项目负责人
				})
				http.get('/api/erp/files/employee/erpEmployeeFile/queryPayGradeByEmpId', { empId: this.model.projectLeading }).then(response => {
					distributionDtList[0].dayCost = response.result
				})
			}
			return distributionDtList
		},
    getFieldsValue(key, value) {
      if (key === '是否关联任务节点' || key === '是否关联进度') {
        return value === '1' ? '是' : '否'
      }
      return value
    },
    // 选择项目名称
    async onChangeProjectName(event) {
      if (!event) {
        this.$set(this.model, 'projectName', undefined) // 项目名称
        this.$set(this.model, 'bail', undefined) // 保证金
        this.$set(this.model, 'finalNo', undefined) // 项目编号
        this.$set(this.model, 'teamName', undefined) // 经营团队
        this.$set(this.model, 'undertaker', undefined) // 项目承接人
        this.$set(this.model, 'projectEstablishDate', undefined) // 立项日期
        this.$set(this.model, 'signUnit', undefined) // 签订单位
        this.$set(this.model, 'year', undefined) // 业绩归属年度
        this.$set(this.model, 'ownerUnit', undefined) // 业主单位
        this.$set(this.model, 'contacts', undefined) // 联系人
        this.$set(this.model, 'contactTel', undefined) // 联系方式
        this.$set(this.model, 'areaCode', undefined) // 项目所在地址
        this.$set(this.model, 'projectAddress', undefined) // 项目所在详细地址
        this.$set(this.model, 'projectSource', undefined) // 项目来源
        this.$set(this.model, 'estimatedContractAmount', undefined) // 预计合同额
        this.$set(this.model, 'estimatedContractcapitalChineseAmount', undefined) // 预计合同额大写
        this.$set(this.model, 'establishReason', undefined) // 立项事由及说明
        this.$set(this.model, 'attachment', undefined) // 项目附件

        this.$set(this.model, 'categoryName', undefined) // 业务分类
        this.$set(this.model, 'categoryCode', undefined) // 业务分类
        this.$set(this.model, 'contractRate', undefined) // 合同占比(%)
        this.$set(this.model, 'contractAmount', undefined) // 合同分配额(元)
        this.$set(this.model, 'cutContractAmount', undefined) // 切割合同额(元)

        this.$set(this.model, 'productTeam', undefined) // 生产团队
        this.$set(this.model, 'productCompanyId', undefined) // 生产公司
        this.$set(this.model, 'taskId', undefined) // 任务编号
        this.priceFormData = [] // 清空款项进度
        return false
      }
      // this.queryPaymentListByProjectId(event.id) // 获取款项进度列表
      // this.queryPaymentNodeListByMainId(event.id)
      this.getQueryByEntity(event.id) // 获取履约保证金
      // this.queryTaskNodeListByMainId(event.id) //  获取任务进度
      this.$set(this.model, 'projectName', event.projectName) // 项目名称
      this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
			this.$set(this.model, 'teamName', event.oldTeamId ? event.oldTeamId : event.teamName) // 经营团队
      this.$set(this.model, 'undertaker', event.undertaker) // 项目承接人
      this.$set(this.model, 'projectEstablishDate', event.projectEstablishDate) // 立项日期
      this.$set(this.model, 'signUnit', event.signUnit) // 签订单位
      this.$set(this.model, 'year', event.year) // 业绩归属年度
      this.$set(this.model, 'ownerUnit', event.ownerUnit) // 业主单位
      this.$set(this.model, 'contacts', event.contacts) // 联系人
      this.$set(this.model, 'contactTel', event.contactTel) // 联系方式
      this.$set(this.model, 'areaCode', event.areaCode) // 项目所在地址
      this.$set(this.model, 'projectAddress', event.projectAddress) // 项目所在详细地址
      this.$set(this.model, 'projectSource', event.projectSource) // 项目来源
      this.$set(this.model, 'estimatedContractAmount', event.estimatedContractAmount) // 预计合同额
      this.$set(this.model, 'estimatedContractcapitalChineseAmount', event.estimatedContractcapitalChineseAmount) // 预计合同额大写
      this.$set(this.model, 'establishReason', event.establishReason) // 立项事由及说明
      this.$set(this.model, 'attachment', event.attachment) // 项目附件
      this.cust_lxr = "erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id='" + event.ownerUnit + "'"

      this.$set(this.model, 'categoryName', undefined) // 业务分类
      this.$set(this.model, 'categoryCode', undefined) // 业务分类
      this.$set(this.model, 'contractRate', undefined) // 合同占比(%)
      this.$set(this.model, 'contractAmount', undefined) // 合同分配额(元)
      this.$set(this.model, 'cutContractAmount', undefined) // 切割合同额(元)

      this.$set(this.model, 'productTeam', undefined) // 生产团队
      this.$set(this.model, 'productCompanyId', undefined) // 生产公司
      this.$set(this.model, 'taskId', undefined) // 任务编号
    },

    // 选择任务编号
    onTaskIdInput({ data: event }) {
      if (!event) {
        this.$set(this.model, 'categoryName', undefined) // 业务分类
        this.$set(this.model, 'categoryCode', undefined) // 业务分类
        this.$set(this.model, 'contractRate', undefined) // 合同占比(%)
        this.$set(this.model, 'contractAmount', undefined) // 合同分配额(元)
        this.$set(this.model, 'cutContractAmount', undefined) // 切割合同额(元)

        this.$set(this.model, 'productTeam', undefined) // 生产团队
        this.$set(this.model, 'productCompanyId', undefined) // 生产公司
        return false
      }
      this.getTaskNodeList(1, '', this.model.projectId, event.id) // 获取任务进度
      this.getPaymentList(1, '', this.model.projectId, event.id) // 获取款项进度
      this.getMemberList(1, '', this.model.projectId, event.id) // 查看成员
      this.getTemplateId(this.model.taskId)

      this.$set(this.model, 'categoryName', event.categoryName) // 业务分类
      this.$set(this.model, 'categoryCode', event.categoryCode) // 业务分类
      this.$set(this.model, 'contractRate', event.contractRate) // 合同占比(%)
      this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)
      this.$set(this.model, 'cutContractAmount', event.cutContractAmount) // 切割合同额(元)

      this.$set(this.model, 'productTeam', event.productTeam) // 生产团队
      this.$set(this.model, 'productCompanyId', event.productCompanyId) // 生产公司

      this.$set(this.model, 'outsourcingFee', event.outsourcingFee) // 委外费
      this.$set(this.model, 'travelFee', event.travelFee) // 差旅费
      this.$set(this.model, 'professionReviewFee', event.professionReviewFee) // 专家评审费
      this.$set(this.model, 'otherCost', event.otherCost) // 其他成本

      this.$set(this.model, 'taskType', event.taskType) // 任务类型
      this.$set(this.model, 'executeDepart', event.executeDepart) // 实施部门
      this.$set(this.model, 'minister', event.minister) // 部门负责人
      this.$set(this.model, 'projectLeading', event.projectLeading) // 项目负责人
    },

    getQueryByEntity(id) {
      var params = {
        preProjectId: id,
        feeCategory: '2',
        bpmStatus: '3',
      }
      // 查看项目保证金
      http.get('/api/erp/finance/deposit/erpFinanceProjectDepositBill/queryByEntity', params).then((res) => {
        if (res.success) {
          let data = res.result
          this.$set(this.model, 'bail', data.remittanceAmount)
          // this.$set(this.validatorRules, 'collectionDate', [{ required: true, message: '请选择应收日期!' }]);
          // this.$set(this.validatorRules, 'paymentDesc', [{ required: true, message: '请填写款项节点说明!' }]);
        } else {
          this.$set(this.model, 'bail', undefined)
          // this.$delete(this.validatorRules, 'collectionDate');
          // this.$delete(this.validatorRules, 'paymentDesc');
        }
      })
    },

    // 获取款项进度列表
    queryPaymentListByProjectId(taskId) {
      this.priceFormData = []
      http.get('/api/erp/omc/task/erpOmcTaskDistribution/queryTaskPaymentList', { taskId }).then((res) => {
        if (res.success) {
          this.priceFormData = res.result || []
        }
      })
    },
    // 编辑获取款项进度列表
    queryPaymentNodeListByMainId(id) {
      if (!id) {
        return false
      }
      this.priceFormData = []
      this.progressNodeVoLoading = true
      http
        .get('/api/erp/omc/task/erpOmcTaskDistribution/queryPaymentNodeListByMainId', { id })
        .then((res) => {
          if (res.success) {
            this.priceFormData = res.result || []
          } else {
            this.queryPaymentListByProjectId(this.model.taskId) // 获取款项进度列表
          }
        })
        .finally(() => {
          this.progressNodeVoLoading = false
        })
    },
    // 编辑获取任务进度列表
    queryTaskNodeListByMainId(id) {
      if (!id) {
        return false
      }
      this.templateLoading = true
      this.templateDataList = []
      http
        .get('/api/erp/omc/task/erpOmcTaskDistribution/queryTaskNodeListByMainId', { id })
        .then((res) => {
          if (res.success) {
            this.templateDataList = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },

    // 选择实施部门
    onExecuteDepartInput(obj) {
      const item = obj[0] || {}
      if (!item.minister) {
        this.$set(this.model, 'minister', undefined)
        return false
      }
      // 赋值部门负责人
      queryUsersByUsernames({ usernames: item.minister }).then((res) => {
        var idsArr = []
        var ids = ''
        if (res && res.length) {
          res.map((value) => {
            idsArr.push(value.empId)
          })
        }
        ids = idsArr.toString()

        this.$set(this.model, 'minister', ids)
      })
    },
		// 点击项目负责人获取数据
		handleProjectLeadingBack(item) {
			if (this.extendUrlParams.node === 'xxmfzr') {
				if (this.model.projectLeading) {
					this.formData = this.addProjectLeading(this.formData, item.realname)
				} else {
					if (this.formData && this.formData.length) {
						// 全部置为false
						this.formData.forEach((item) => {
							item.isProjectLeading = false
						})
					}
				}
			}
		},

    // 选择进度模板
    getTemplateList(data) {
			this.$set(this.model, 'confirmIncomeMethod', data.confirmIncomeMethod || '') // 收入确认方式
			this.$set(this.model, 'isAddChildNode', data.isAddChildNode || '') // 允许添加子节点
      this.$set(this.model, 'templateName', data.templateName)
			this.$set(this.model, 'isTemplateCancel', '1')
      erpProgressTemplateDtList({ mainId: data.id }).then((res) => {
				if (res.success) {
					// 后端无良心，需要前端自己处理，当选择了“允许添加子节点”需要在每一个节点里面塞isAddChildNode值最后一个节点不用塞
					let isAddChildNode = data.isAddChildNode
					this.templateDataList = res.result.map((item, index) => {
						item.templateNodeId = item.id
						item.id = this.getRandomNum()
						if (index === res.result.length - 1) {
							item.isAddChildNode = '0'
						} else {
							item.isAddChildNode = isAddChildNode
						}
						return item
					})
					this.priceFormData.forEach((i) => {
					  i.isCollectionPayment = null
					  i.isCollectionPayment_dictText = null
					  i.isRelatedTask = null
					  i.isRelatedTaskNode = null
					  i.isRelatedTaskNode_dictText = null
					  i.isRelatedTask_dictText = null
					  i.taskCompleteStatus = null
					  i.taskCompleteStatus_dictText = null
					  i.taskNodeId = null
					  i.taskNodeId_dictText = null
						i.taskProgress = null
					})
				}
      })
    },

    // 获取唯一随机数
    getRandomNum() {
      let date = new Date().valueOf() // 获取时间戳
      let txt = '1234567890' // 生成的随机机器码
      let len = 19 // 机器码有多少位
      let pwd = '' // 定义空变量用来接收机器码
      for (let i = 0; i < len; i++) {
        pwd += txt.charAt(Math.floor(Math.random() * txt.length)) // 循环机器码位数随机填充
      }
      return date + pwd
    },
    // 款项进度完善
    PerfectTaskChange(val) {
      this.priceFormData.forEach((it, i) => {
        if (it.id === val.id) {
          this.priceFormData.splice(i, 1, val)
        }
      })
    },
    // 获取任务进度
    getTaskNodeList(handlerType, id, projectId, taskId) {
      http
        .get('/api/erp/omc/task/erpOmcTaskDistributionChange/queryTaskNodeList', { handlerType, id, projectId, taskId, isChild: '0' })
        .then((res) => {
          if (res.success) {
						this.templateDataList = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },
    // 获取款项进度
    getPaymentList(handlerType, id, projectId, taskId) {
      http
        .get('/api/erp/omc/task/erpOmcTaskDistributionChange/queryPaymentList', { projectId, id, taskId, handlerType })
        .then((res) => {
          if (res.success) {
            this.priceFormData = res.result || []
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },

    // 查看成员列表
    getMemberList(handlerType, id, projectId, taskId) {
      http
        .get('/api/erp/omc/task/erpOmcTaskDistributionChange/queryMemberList', { projectId, id, taskId, handlerType })
        .then((res) => {
          if (res.success) {
            this.formData = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },
    // 获取任务进度模板
    getTemplateId(id) {
      queryPageList({ id }).then((res) => {
        if (res.success) {
          var event = res.result.records[0]
          this.$set(this.model, 'templateId', event.templateId)
          this.$set(this.model, 'templateName', event.templateName)
        }
      })
    },
    /**
     * 弹窗点击确认
     */
    handleConfirmModalConfirm() {
      this.formData = []
      this.confirmModal = false
    },
    /**
     * 弹窗点击取消
     */
    handleConfirmModalCancel() {
      // 还原修改的数据
      if (this.resetKey) {
        let realKey = this.resetKey.replace('backUp', '')
        realKey = realKey[0].toLowerCase() + realKey.slice(1)
        this.isReset = true
        this.$set(this.model, realKey, this[this.resetKey])
        setTimeout(() => (this.isReset = false), 0)
      }
      this.confirmModal = false
    },
    /**
     * 修改值时，检查是否需要弹出对话框确认修改
     * 取消 modal 的时候，需要将值还原
     * @param {String} key BasicForm 中的key值
     * @param {Function} fn 回调函数
     * @param {any} data 回调函数参数
     */
    checkSwitch(key, fn, data) {
      this.$nextTick(() => {
        if (this.isReset) return
        const firstChar = key[0].toUpperCase()
        key = firstChar + key.slice(1)
        const oldData = this[`backUp${key}`]
        if (oldData && oldData !== this.model[key]) {
          this.confirmModal = true
          this.resetKey = `backUp${key}`
        } else {
          fn && fn(data)
        }
      })
    },
    projectChange() {},
    handleChangeFoldTeamId(val, num = 0) {
      let v = val.id
      this.foldTeamIdChange(v, num)
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    foldTeamIdChange(id, edit) {
      if (this.model.exportTeamId == id) {
        this.$u.toast('调入团队不能和调出团队相同')
        this.$set(this.model, 'foldTeamId', null)
        this.$set(this.model, 'foldWarehouse', undefined)
        return false
      }
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.foldWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'foldWarehouse', undefined)
          }
          const data = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.foldWarehouseList = [data]
        } else {
          this.$u.toast(res.message)
        }
      })
    },
    // 新增物料
    handleAddMember() {
      this.index = null
      this.showFormModal = true
    },
    handleChangeExportTeamId(v, num = 0) {
      if (v != this.exportTeamId) {
        this.exportTeamIdChange(v, num)
      }
      this.exportTeamId = this.model.exportTeamId
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    exportTeamIdChange(row, edit = false) {
      const id = row.id
      if (this.model.foldTeamId == id) {
        this.model.exportTeamId = this.exportTeamId
        this.$u.toast('调入团队不能和调出团队相同')
        return false
      }
      // 清空子表
      // this.$refs.cannibalizeDetailList.reset()
      this.warehouse = null
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.exportWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'exportWarehouse', undefined)
            this.warehouse = null
          }
          const list = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.exportWarehouseList = [list]
        } else {
          this.$u.toast(res.message)
        }
      })
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
    },
		closePriceFormModal() {
		  this.$refs.priceForm.reset()
		  this.basicForm = {}
		  this.index = null
			this.showPriceFormModal = false
		},
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, { ...data })
      } else {
        this.formData.push(data)
      }
      // this.initBuyerInfo()
    },
    // ----------不同子表分界线----------
    handleCopyPriceForm([item, index]) {
      this.priceFormData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditPriceForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showPriceFormModal = true
    },
    handleRemovePriceForm(item) {
      this.priceFormData = this.priceFormData.filter((i) => i !== item)
    },
    openPriceFormModal() {
      this.$refs.priceForm.basicForm = this.basicForm
    },
    addPriceForm() {
      this.index = null
      this.showPriceFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handlePriceFormSubmit([data, index]) {
      this.showPriceFormModal = false
      if (typeof index === 'number') {
        this.$set(this.priceFormData, index, data)
      } else {
        this.priceFormData.push(data)
      }
      this.$nextTick(() => {
        this.$refs.collapse.init()
      })
      // this.initBuyerInfo()
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ prefix: 'RWBG', subSystemCode: '05' })
      this.model.billNo = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.billNo //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.handlerId = this.userInfo.empId //当前登录人
      this.model.handlerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      for (const key in data) {
        if (Object.hasOwnProperty.call(this.model, key)) {
          this.model[key] = data[key]
        }
      }
    },
		validateNoDuplicateProjectMembers(list) {
			const duplicates = list.filter((item, index) => 
				list.findIndex(i => i.projectMember === item.projectMember) !== index
			);
			if (duplicates.length > 0) {
				return false; // 验证失败
			}
			return true; // 验证通过
		},
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        if (this.extendUrlParams.node === 'xxmfzr') {
          // 项目成员
          if (!this.formData || !this.formData.length) {
            this.$u.toast('项目成员至少有一条数据')
            return Promise.reject('项目成员至少有一条数据')
          }
					const isMemberError = this.formData.some((item) => {
					  return !item.projectMember || (item.contractAmount===undefined || item.contractAmount===null||item.contractAmount==='') || (item.expectWorkTime===undefined || item.expectWorkTime===null||item.expectWorkTime==='') || (item.projectPerformance===undefined || item.projectPerformance===null||item.projectPerformance==='')
					})
					if (isMemberError) {
					  this.$u.toast('请完善项目成员信息')
					  return Promise.reject('请完善项目成员信息')
					}
					const isRepeat = this.validateNoDuplicateProjectMembers(this.formData);
					if (!isRepeat) {
						this.$u.toast('请勿重复添加项目成员!')
						return Promise.reject('请勿重复添加项目成员!')
					}
          // 款项进度
          // 判断款项进度是否全部完善
          // function isNumber(value) {
          //   return /^-?\d+(\.\d+)?$/.test(value)
          // }
          const isPriceError = this.priceFormData.some((item) => {
            return !item.taskNodeId
          })
          if (this.priceFormData && this.priceFormData.length && isPriceError) {
            this.$u.toast('请完善款项进度！')
            return Promise.reject('请完善款项进度！')
          }
          // 当任务类型为检验检测时：是否出具报告（必填）
          if (this.model.taskType === '2') {
            if (!this.model.isOutReport) {
              this.$u.toast('请选择是否出具报告')
              return Promise.reject('请选择是否出具报告')
            }
          }
          function parse(num) {
            return Number(num) || 0
          }
          const total = this.formData.reduce((total, item) => {
            return new Decimal(parse(item.contractAmount)).plus(total).toNumber()
          }, 0)
          if (total !== parse(this.model.contractAmount)) {
            this.$u.toast('合同分配额总和必须等于任务委托合同额！')
            return Promise.reject('合同分配额总和必须等于任务委托合同额！')
          }
        }
        return Promise.resolve()
      })
    },
		
		// 查询流程流转信息 -- 获取下一节点信息
		getProcessTaskTrans(taskId){
			getProcessTaskTransInfo({ taskId }).then(res => {
				if(res.success){
					this.resultObj = res.result
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error'
					})
				}
			}).catch(err => {
				console.log(err);
			})
		},
    async onSubmit() {
      await this.validateForm()
			var _this = this
      try {
        this.loading = true
        const response = await edit({
          ...this.model,
          distributionDtList: this.formData,
          progressNodeVoList: this.priceFormData,
          progressVoList: this.templateDataList
        })
        if (response.success) {
					this.$refs.uToast.show({
						message: '提交成功',
						type: 'success',
						complete () {
							_this.onAudit()
						}
					})
          this.isSubmit = true
        } else {
					this.$refs.uToast.show({
						message: response.message,
						type: 'error'
					})
				}
      } finally {
        this.loading = false
      }
    },

    onAudit() {
      if (!this.isSubmit) {
        uni.showToast({
          title: '请完善表单后审核',
          icon: 'none',
        })
        return false
      }
      var that = this
      uni.navigateTo({
        url: '/pages/synergy/ErpOmcTaskChangeForm' + `?item=${encodeURIComponent(JSON.stringify(that.processModel).replace(/%/g, '%25'))}`,
        success: function (data) {
          // 通过eventChannel向被打开页面传送数据
          var params = {
            nodeObj: that.dataNodeObj,
            tabvalue: that.tabvalue,
          }
          data.eventChannel.emit('sendMessage', params)
        },
        fail: function (err) {
          this.$refs.uToast.show({
            message: '请联系管理员配置',
            type: 'error',
          })
        },
      })
    },
    async onDraft() {
      await this.validateForm()
    },
  },
  watch: {
    expectWorkTime(val) {
      this.model.expectWorkTime = val
    },
    workCost(val) {
      this.model.workCost = val
    },
    totalProjectBudget(val) {
      this.model.totalProjectBudget = val
    },
		totalProductPerformance(val) {
      this.model.totalProductPerformance = val
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
